<?php

	/* functions.php
	* Defines various functions used across the tool.
	* */

	# The ezsql utility.
	require_once "./ezsql/ez_sql_core.php" ;
	require_once "./ezsql/ez_sql_mysql.php" ;

	require_once "./kalike.inc.php";

	
	function open_connection() {
		$db = new ezSQL_mysql( USER, PASSWORD, DBNAME, DBHOST );
		
		return $db;
	}
	
	function open_connection_pdo() {
		$db = new PDO ( sprintf('mysql:host=%s;dbname=%s', DBHOST, DBNAME), USER, PASSWORD );		
		return $db;
	}
	
	function get_header() {
		$header = '
			<html>
			<!doctype html>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

			<head>
			<script type="text/javascript" src="js/jquery.min.js"></script>
			<script type="text/javascript" src="js/json2.js"></script>
			<link type="text/css" rel="stylesheet" href="css/kalike.css">
			</head>

			<body>
			<div id="container">
			
		';

		echo $header;
	}

	function get_footer() {
		$footer = "</div> <!-- Close of class='container' --> 
		<script type='text/javascript' src='js/jquery.min.js'></script>
		<script src='js/kalike.js'></script>		
		</body> </html>";
		echo $footer;
	}

	/* This function returns the current date, and time in the format
	 * MM-DD-YYYY HH:MM:SS
	 */
	 
	function get_curr_time() {
		$today = getdate();
		
		printf( "%s-%s-%s %s:%s:%s", $today['month'], 
									$today['mday'], 
									$today['year'], 
									$today['hour'], 
									$today['minutes'], 
									$today['seconds'] 
				);
		return;
	}
	
	function debug_log( $debug_msg, $criticality, $origin ) {
	
		if ( defined ( 'KALIKE_DEBUG' ) ) {
			printf("%s :%s :%s ", get_curr_time(), $criticality, $origin);
		}
	}
	
	
	function process_action( $action ) {
		global $actions;
		if ( ! empty( $action ) and in_array ( $action, $actions ) ) {
			get_header();
			
			switch( $action ) {
				case "create_test":
?>
				<div id="input">
				<h3>Create a test</h3>
						<form id="create_test" name="f_create_test" action="ajaxify.php" method="POST">
						<label for="test_name">Name of the test</label>
						<input type="hidden" name="action" value="create_test">
						<input type="text" name="test_name" id="test_name" size="55" placeholder="How'd you like to name this test.?" required>
						<br><label for="test_purpose"> Purpose/introduction of test</label> <textarea rows="5" cols="45" type="text" name="test_purpose" id="test_purpose" placeholder="Describe the purpose of this test or introduce it." required></textarea>
						
						<br><label for="strict" title="If checked, then the candidate will not be made aware of the right answer if he/she answers a question wrong.">Strict test?</label>
						<input type="checkbox" id="strict" name="strict" title="If checked, then the candidate will not be made aware of the right answer if he/she answers a question wrong.">
						<br><label for="time"> Time limit(in minutes)</label>
						<input type="text" name="time" id="time" placeholder="How many minutes?">
						<br><input type="reset" name="reset" value="Reset the form!">
						<input type="submit" name="submit" value="Create test">
					</form>						
				</div>
				<div id="output">
				</div>
<?php
					break;
				default:
					echo "unhandled at the moment!";
					break;
			}			
			
			get_footer();
		}	
	}

	function __die( $msg ) {
		/*  __die() is called when an error is seen. This method just prints the error, and
		* with </body>, and </html> tags.
		*/
		
		$msg .= "</body> </html>";

		die( $msg );
	}
	
	function get_username_by_id ( $user_id ) {
		$db = open_connection();
		
		$user_name = $db->get_var( sprintf("SELECT user_name FROM kalike_users WHERE user_id='%s'", $user_id ) );
		return $user_name;
	}
	
	
	function get_user_id ( $username ) {
		/* 
		 * Returns the current user's user_id, if empty username is passed
		 * else,
		 * the given user's user_id
		 */
		 
		$db = open_connection();
		$username = ( empty( $username ) ) ? $_SESSION['user'] : $username;

		$user_id = $db->get_var( sprintf("SELECT user_id FROM kalike_users WHERE user_name='%s'", $username ) );
		return $user_id;
	}
	
	
	function get_salt( $u ) {
		$db = open_connection();
		
		$db->get_row( sprintf("SELECT user_name FROM kalike_users WHERE user_name=%s", $u) );
		if ( $db->user_name == "" ) {
			die( sprintf( "User %s is not registered.", $u ) );
		}		
	}
	
	function get_test_creator ($db, $test_id) {	
		try {
			$stmnt = $db->prepare( "SELECT test_creator FROM test_details WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );		
			$test_creator = $result["test_creator"];			
		} catch( PDOException $e ) {
			echo "Could not count total questions: " . $e->getMessage();
		}
		
		return $test_creator;
	}
	
	function check_test_ownership( $db, $test_id ) {		
		try {
			$stmnt = $db->prepare( "SELECT test_id FROM test_details WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );		
			$test_id = $result["test_id"];
		} catch( PDOException $e ) {
			echo "Could not count total questions: " . $e->getMessage();
		}
		
		if ( ! $test_id ) {
			die ("Invalid test_id was passed or you don't have access to this test.");
		}
		
		$this_user = get_user_id ( $_SESSION['user'] );
		$test_creator = get_test_creator ($db, $test_id);
		
		if ( $this_user !== $test_creator ) {
			return false;
		} else {
			return true;
		}
	}
	
	function test_id_exists( $test_id ) {
		$db_pdo = open_connection_pdo();
		
		$statement = $db_pdo->prepare("SELECT test_id FROM test_details WHERE test_id=:test_id");
		$statement->bindParam( ":test_id", $test_id );
		
		$statement->execute();		
	}

	function get_total_questions_count( $db, $test_id ) {		
		try {
			$stmnt = $db->prepare( "SELECT count(*) AS total_questions FROM questions WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );		
			$total_questions = $result["total_questions"];			
		} catch( PDOException $e ) {
			echo "Could not count total questions: " . $e->getMessage();
		}
		return $total_questions;
	}
	
	function get_all_question_ids( $db, $test_id ) {
		try {
			$stmnt = $db->prepare( "SELECT question_number FROM questions WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$question_numbers = $stmnt->fetchAll( PDO::FETCH_ASSOC );		
		} catch( PDOException $e ) {
			echo "Could not count total questions: " . $e->getMessage();
			return;
		}
		return $question_numbers;
	}
	
	function get_test_owner( $db, $test_id ) {		
		try {
			$stmnt = $db->prepare( "SELECT test_creator FROM test_details WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );
			$test_creator = $result["test_creator"];			
		} catch( PDOException $e ) {
			echo "Could not get test owner name: " . $e->getMessage();
		}
		return $test_creator;
	}
	
	function check_test_id( $db, $test_id ) {
		try {
			$stmnt = $db->prepare( "SELECT test_id FROM test_details WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );
			
		} catch( PDOException $e ) {
			echo "Could not get test owner name: " . $e->getMessage();
		}
		return ( $test_id == $result["test_id"] ? true : false );
	}
	
	function get_test_title( $db, $test_id ) {
		try {
			$stmnt = $db->prepare( "SELECT test_title FROM test_details WHERE test_id=:test_id" );
			$stmnt->bindParam( ":test_id", $test_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );
		} catch( PDOException $e ) {
			echo "Could not get test title name: " . $e->getMessage();
		}
		return $result["test_title"];
	}
	
	function get_question_title( $db, $t_id, $q_id ) {
		try {
			$stmnt = $db->prepare( "SELECT question_title FROM questions WHERE test_id=:t_id AND question_number=:q_id" );
			$stmnt->bindParam( ":t_id", $t_id );
			$stmnt->bindParam( ":q_id", $q_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );
		} catch( PDOException $e ) {
			echo "Could not get test title name: " . $e->getMessage();
		}
		return ( $result["question_title"] != "" ) ? $result["question_title"]:false;
	}
	
	function get_question_type( $db, $t_id, $q_id ) {
		try {
			$stmnt = $db->prepare( "SELECT question_type FROM questions WHERE test_id=:t_id AND question_number=:q_id" );
			$stmnt->bindParam( ":t_id", $t_id );
			$stmnt->bindParam( ":q_id", $q_id );
			$stmnt->execute();
		
			$result = $stmnt->fetch( PDO::FETCH_ASSOC );
		} catch( PDOException $e ) {
			echo "Could not get test title name: " . $e->getMessage();
		}
		return $result["question_type"];
	}

	function get_mul_choice_answer_maker( $db, $t_id, $q_id ) {
		
		try {
			$stmnt = $db->prepare( "SELECT choice_text, is_right_answer FROM multiple_choice_answers WHERE test_id=:t_id AND question_number=:q_id" );
			$stmnt->bindParam( ":t_id", $t_id );
			$stmnt->bindParam( ":q_id", $q_id );
			$stmnt->execute();
		
			$result = $stmnt->fetchAll( PDO::FETCH_ASSOC );
		
		} catch ( PDOException $e ) {
			echo "Could not read multiple choice answer maker: " . $e->getMessage();
		}
		return $result;
	}
	
	function get_match_following_answer_maker( $db, $t_id, $q_id ) {
		try {
			$stmnt = $db->prepare( "SELECT choice_number, left_choice_text, right_choice_text FROM match_following_answers WHERE test_id=:t_id AND question_id=:q_id ORDER BY choice_number" );
			$stmnt->bindParam( ":t_id", $t_id );
			$stmnt->bindParam( ":q_id", $q_id );
			$stmnt->execute();
		
			$result = $stmnt->fetchAll( PDO::FETCH_ASSOC );
			
			
		} catch ( PDOException $e ) {
			echo "Could not read multiple choice answer maker: " . $e->getMessage();
		}
		return $result;
	}
?>


